#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct
{
    int* a;
    int front; // 头
    int rear;  // 尾的下一位
    int k;     // 有效数字
} MyCircularQueue;


MyCircularQueue* myCircularQueueCreate(int k)
{
    MyCircularQueue* obj = (MyCircularQueue*)malloc(sizeof(MyCircularQueue));
    obj->a = (int*)malloc(sizeof(int) * (k + 1));

    obj->front = obj->rear = 0;
    obj->k = k;

    return obj;
}

bool myCircularQueueIsEmpty(MyCircularQueue* obj)
{
    return obj->front == obj->rear;
}

bool myCircularQueueIsFull(MyCircularQueue* obj)
{
    return (obj->rear + 1) % (obj->k + 1) == obj->front;
}

bool myCircularQueueEnQueue(MyCircularQueue* obj, int value)
{
    if (myCircularQueueIsFull(obj)) {
        return false;
    }

    obj->a[obj->rear] = value;
    obj->rear++;
    obj->rear %= (obj->k + 1);

    return true;
}

bool myCircularQueueDeQueue(MyCircularQueue* obj)
{
    if (myCircularQueueIsEmpty(obj)) {
        return false;
    }

    obj->front++;
    obj->front %= (obj->k + 1);

    return true;
}

int myCircularQueueFront(MyCircularQueue* obj)
{
    if (myCircularQueueIsEmpty(obj)) {
        return -1;
    }

    return obj->a[obj->front];
}

int myCircularQueueRear(MyCircularQueue* obj)
{
    if (myCircularQueueIsEmpty(obj)) {
        return -1;
    }

    return obj->a[(obj->rear - 1 + obj->k + 1) % (obj->k + 1)];
}

void myCircularQueueFree(MyCircularQueue* obj)
{
    free(obj->a);
    free(obj);

    obj = NULL;
}

int main()
{
    MyCircularQueue* cq = myCircularQueueCreate(4); // 最多存放四个有效数据

    int i = 0;
    // 存进去 1 2 3 4，但是只是打印队头1
    while (myCircularQueueEnQueue(cq, ++i)) {
        int front = myCircularQueueFront(cq);
        printf("%d ", front);
    }
    putchar('\n');

    i = 0;
    // 出去 1 2 3 4，打印尾部 4 4 4，最后一次为空，打印-1
    while (myCircularQueueDeQueue(cq)) {
        int back = myCircularQueueRear(cq);
        printf("%d ", back);
    }
    putchar('\n');

    myCircularQueueFree(cq);

    return 0;
}